﻿using Microsoft.AspNetCore.Http;
using NLog;
using NLog.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DearlerPlatform.Common.ExceptionGlobal
{
    /// <summary>
    /// 自定义全局异常中间件
    /// </summary>
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception exception)
            {
                // 你可以在这里进行相关的日志记录
                var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
                logger.Error("异常请求类型:"+context.Request.Method + "  异常请求路径:"+context.Request.Path);
                logger.Error(exception);
                await HandleExceptionAsync(context, exception);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            // 返回信息格式
            context.Response.ContentType = "application/json";
            // 返回的Http 状态码
            context.Response.StatusCode = 500;
            //返回的消息内容
            var responseModel = ApiResult<string>.Fail("服务器出现异常，异常时间:"+DateTime.Now.ToString()+" 请联系管理员处理。异常信息:"+exception.Message);

            //返回消息
            await context.Response.WriteAsync(responseModel.ToJsonString());
        }
    }
}
